package demo.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @ClassName FieldCollector
 * @Description
 * @Author 47980
 * @Date 2020/6/10 21:22
 * @Version V_1.0
 **/
public class FieldCollector {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //获取Class对象
        Class clazz = Class.forName("demo.reflect.ReflectTarget");

        //1.获取所有公有的字段
        System.out.println("================= 获取所有公有的字段 =================");
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }

        //2.获取所有的字段
        System.out.println("================= 获取所有的字段 =================");
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println(field);
        }

        //3.获取单个特定公有的字段
        System.out.println("================= 获取单个特定公有的字段 =================");
        Field name = clazz.getField("name");
        System.out.println("public field name = "+name);
        ReflectTarget reflectTarget = (ReflectTarget)clazz.getConstructor().newInstance();
        //4.给获取到的Field赋值
        name.set(reflectTarget, "带反射一号");
        //5.验证对应的name值
        System.out.println("验证name：" + reflectTarget.name);

        //6.获取单个私有的Field
        System.out.println("================= 获取单个私有的Field =================");
        Field targetInfo = clazz.getDeclaredField("targetInfo");
        //暴力破解
        targetInfo.setAccessible(true);
        System.out.println(targetInfo);
        targetInfo.set(reflectTarget, "12098274554");
        System.out.println("验证信息"+reflectTarget);
    }
}
